/*
* 转链
* */

import AppConfig from "../config/appConfig";
import {TimeStamp,TimeStampToHoldTime} from "../utils/utils";
import AppStore from "../store/appStore";
import axiosUtil from "../utils/axiosUtil";
import md5 from 'md5';
import  viewUtil from '../utils/viewUtil';
import {IsNullObject} from '../utils/utils';
import {CreateHaoDanwangList} from "./modeCtr";

import {signJD} from '../utils/JDUtil';

export function ChangePromotionUrl(item) {

  if (item.TypeFrom === AppConfig.TaoBao){

    return Tao_BaoData_Rate(item)
    // return TaoBao(item);
  }
  if (item.TypeFrom === AppConfig.JinDong){
    return JinDong(item)
  }


  if (item.TypeFrom === AppConfig.PingDuoDuo){
    return PingDuoDuo(item);
  }
  return new Promise(resolve => {
    resolve(null);
  })
}

export  function  GetPromotionDataStr(item) {
  var  data = ''
  if (item.TypeFrom === AppConfig.TaoBao){
    data="淘宝:\n"
    if (item.Tpwd !==''){
      data=data+"   已复制打开淘客户端:\n"  +item.Tpwd+"\n"
    } else {
      data=data+"   打开淘宝客户端粘贴到搜索栏:\n"  +item.CouponUrl+"\n"
    }

    // data=data+"   淘宝客户端商品链接粘贴到搜索栏:\n"  +item.item_url
  }

  if (item.TypeFrom === AppConfig.JinDong){
    // console.log(item)
    data="京东:\n"
    if (item.clickURL !== ""){
      data=data+"   直接点击优惠卷:\n"  +item.clickURL
    }else {
      data=data+"   直接点击优惠卷:\n"  +item.CouponUrl
    }

    // data= data+"  直接点击商品链接:\n"+item.item_url
  }

  if (item.TypeFrom === AppConfig.PingDuoDuo){
    data="拼多多:\n"
    // data=data+"   优惠卷:"+item.CouponUrl+"\n"
    // data=data+"   长链接:"+item.long_url+"\n"
    data=data+"   直接点击优惠卷:\n"+item.short_url
    // data=data+"   唤醒拼多多app的推广短链接:"+item.mobile_short_url+"\n"
    // data=data+"   唤醒拼多多app的推广长链接:"+item.mobile_url+"\n"
  }
  return data+"\n\n提示：如果没显示优惠卷请回复1,再重新领取！"
}

export function changeTaoLing(Pic,Title,CouponUrl) {
  console.log("转链接")
  return new Promise(resolve => {
    const timestamp = TimeStamp();
    const signStr = AppStore.data.taoBaoApi.app_secret+
      "app_key"+AppStore.data.taoBaoApi.app_key+
      "format"+'json'+
      "logo" + Pic+
      "method"+"taobao.tbk.tpwd.create"+
      "sign_method"+"md5"+
      "text"+Title+
      "timestamp"+timestamp+
      "url"+CouponUrl+
      "v"+"2.0"+
      AppStore.data.taoBaoApi.app_secret;
    const signback = md5(signStr);

    var  url =  AppStore.data.taoBaoApi.api
    var  data ={}

    data.app_key = AppStore.data.taoBaoApi.app_key
    data.format = 'json'
    data.method = "taobao.tbk.tpwd.create"
    data.sign_method = 'md5'
    data.timestamp = timestamp
    data.v = '2.0'
    data.text = Title
    data.url = CouponUrl
    data.logo = Pic
    data.sign =signback.toUpperCase()


    axiosUtil.get(url,data).then(res=>{
      console.log('===========>')
      // console.log(res)
      var dat1 = res.tbk_tpwd_create_response
      if (IsNullObject(dat1)){
        resolve(null)
      } else {
        // item.Tpwd =  res.tbk_tpwd_create_response.data.model //.replaceAll('￥',"+")
        resolve(res.tbk_tpwd_create_response.data.model)
      }
    })
  })
}

//好当网转高佣
function  Tao_BaoData_Rate(item) {
  return new Promise(resolve => {

    Tao_haoDao_Ratesurl(item.Id,item.Title).then(res=>{
      if ( IsNullObject(res)){
        console.log("转高佣失败！")
        resolve(item)
      }else {
        console.log("转后url:"+ res.coupon_click_url)
        item.CouponUrl = res.coupon_click_url
        item.item_url = res.item_url
        item.Tpwd = res.taoword
        resolve(item)
      }
    })
  })
}


export function Tao_haoDao_Ratesurl(itemid,title) {
  // console.log("商品Id :"+itemid)
  return new Promise(resolve =>{
      var data = {}
      data.apikey = AppStore.data.taoBaoApi.haoDanKey
      data.itemid = itemid
      data.pid =  AppStore.data.taoBaoApi.Pid
      data.tb_name =AppStore.data.taoBaoApi.tb_name
      data.get_taoword = 1
      data.title = title

      Taro.request({
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        method:'POST',
        url:AppStore.data.taoBaoApi.ratesurl,
        data:data,
      }).then(res=>{
        // console.log(res.data)
        if (res.data == null){
          viewUtil.ShowToast('获取优惠卷链接失败');
          resolve(null)
        } else {
          if (parseInt(res.data.code) !== 1){
            viewUtil.ShowToast('获取优惠卷链接失败～');
            resolve(null)
          }else{
            resolve({coupon_click_url:res.data.data.coupon_click_url,item_url:res.data.data.item_url,taoword:res.data.data.taoword})
          }
        }
      })
  } )
}

//单品券高效转链
// function TaoBao_ChangeLink(CouponUrl) {
//   console.log(CouponUrl)
//   return new Promise(resolve => {
//     const timestamp = TimeStamp();
//     const signStr = AppStore.data.taoBaoApi.app_secret+
//       "adzone_id"+AppStore.data.taoBaoApi.adzone_id+
//       "app_key"+AppStore.data.taoBaoApi.app_key+
//       "format"+'json'+
//       "method"+"taobao.tbk.coupon.convert"+
//       "sign_method"+"md5"+
//       "timestamp"+timestamp+
//       "url"+CouponUrl+
//       "v"+"2.0"+
//       AppStore.data.taoBaoApi.app_secret;
//     const signback = md5(signStr);
//
//     var  url =  AppStore.data.taoBaoApi.api
//     var  data ={}
//
//     data.adzone_id = AppStore.data.taoBaoApi.adzone_id
//     data.app_key = AppStore.data.taoBaoApi.app_key
//     data.format = 'json'
//     data.method = "taobao.tbk.coupon.convert"
//     data.sign_method = 'md5'
//     data.timestamp = timestamp
//     data.v = '2.0'
//     data.url = CouponUrl
//     data.sign =signback.toUpperCase()
//
//     axiosUtil.get(url,data).then(res=>{
//       console.log(res)
//       // if (IsNullObject(dat1)){
//       //   resolve(null)
//       // } else {
//       //   // item.Tpwd =  res.tbk_tpwd_create_response.data.model //.replaceAll('￥',"+")
//       //   resolve(res.tbk_tpwd_create_response.data.model)
//       // }
//     })
//   })
// }

//转淘口令
function TaoBao(item) {
  return new Promise(resolve => {
    changeTaoLing(item.Pic,item.Title,item.CouponUrl).then(res=>{
      if (res === null)
        resolve(item)
      else {
        item.Tpwd =  res //.replaceAll('￥',"+")
        resolve(item)
      }
    })
  })

  // return new Promise(resolve => {
  //   const timestamp = TimeStamp();
  //   const signStr = AppStore.data.taoBaoApi.app_secret+
  //     "app_key"+AppStore.data.taoBaoApi.app_key+
  //     "format"+'json'+
  //     "logo" + item.Pic+
  //     "method"+"taobao.tbk.tpwd.create"+
  //     "sign_method"+"md5"+
  //     "text"+item.Title+
  //     "timestamp"+timestamp+
  //     "url"+item.CouponUrl+
  //     "v"+"2.0"+
  //     AppStore.data.taoBaoApi.app_secret;
  //   const signback = md5(signStr);
  //
  //   var  url =  AppStore.data.taoBaoApi.api
  //   var  data ={}
  //
  //   data.app_key = AppStore.data.taoBaoApi.app_key
  //   data.format = 'json'
  //   data.method = "taobao.tbk.tpwd.create"
  //   data.sign_method = 'md5'
  //   data.timestamp = timestamp
  //   data.v = '2.0'
  //   data.text = item.Title
  //   data.url = item.CouponUrl
  //   data.logo = item.Pic
  //   data.sign =signback.toUpperCase()
  //
  //   axiosUtil.get(url,data).then(res=>{
  //     var dat1 = res.tbk_tpwd_create_response
  //    if (IsNullObject(dat1)){
  //      resolve(item)
  //    } else {
  //      item.Tpwd =  res.tbk_tpwd_create_response.data.model //.replaceAll('￥',"+")
  //      resolve(item)
  //    }
  //   })
  // })

}

async function JinDong(item) {
  var args = signJD(AppStore.data.jinDongApi.app_key,
                   AppStore.data.jinDongApi.app_secret,
        "jd.union.open.promotion.common.get",{
        promotionCodeReq:{
          couponUrl:item.CouponUrl,
          materialId:item.item_url,//"http://item.jd.com/20175593221.html",
          siteId: AppStore.data.jinDongApi.siteId,
        }
      }
    )

  return  new Promise(resolve => {
    Taro.request({
      url:"https://router.jd.com/api",
      data: args
    }).then(res=>{
      if (IsNullObject(res.data) || IsNullObject(res.data.jd_union_open_promotion_common_get_response)){

          resolve(item)
      }else {

          var result = res.data.jd_union_open_promotion_common_get_response.result
        result = JSON.parse(result)
        if (parseInt(result.code) !== 200){
            resolve(item)
          }else {

            item.clickURL = result.data.clickURL
            resolve(item)
          }
      }
    })
  })

}

function PingDuoDuo(item) {
  return new Promise(resolve => {
    //获取京东商品数据
    const timestamp = TimeStamp();
    const sign =
      AppStore.data.pingDuoDuoApi.client_secret +
      "client_id"+AppStore.data.pingDuoDuoApi.client_id+
      "data_type"+"JSON"+
      "goods_id_list"+"["+item.Id+"]"+
      "p_id" +AppStore.data.pingDuoDuoApi.pid+
      "timestamp" + timestamp+
      "type"+AppStore.data.pingDuoDuoApi.PromotionUrl+
      AppStore.data.pingDuoDuoApi.client_secret;

    const signback = md5(sign);
    var  data = {}
    data.client_id = AppStore.data.pingDuoDuoApi.client_id
    data.data_type = "JSON"
    data.goods_id_list ="["+item.Id+"]"  //奇葩成功
    data.timestamp = timestamp;
    data.p_id = AppStore.data.pingDuoDuoApi.pid;
    data.type = AppStore.data.pingDuoDuoApi.PromotionUrl
    data.sign =signback.toUpperCase()
    var  url = AppStore.data.pingDuoDuoApi.api
    axiosUtil.post(url,data).then(res=>{
      if (res.goods_promotion_url_generate_response ==null){
        viewUtil.ShowToast('获取优惠卷链接失败');
      } else {
        var promotionItem = res.goods_promotion_url_generate_response.goods_promotion_url_list[0]
        item.short_url = promotionItem.short_url
        item.long_url = promotionItem.url
        item.mobile_short_url = promotionItem.mobile_short_url
        item.mobile_url = promotionItem.mobile_url
        resolve(item)
      }
    })
  })

}
